#!/bin/bash
# author ryb


# 函数
function isgreen() {
    if [ $? -eq 0 ]; then
        echo -e "\e[32m$1==========>succeed\e[0m"
    else
        echo -e "\e[31m$1==========>failed\e[0m"
        exit 1
    fi
}

# 全局变量
config_file="/etc/chrony.conf"

# 安装软件
echo "安装chrony..."
if ! rpm -q chrony >/dev/null; then
    yum install -y chrony >/dev/null 2>&1
    isgreen "installed chrony"
else
    echo >/dev/null
    isgreen "installed chrony"
fi

# 修改配置文件
echo "修改配置文件"
if [ ! -f "$config_file.bak" ]; then
    cp "$config_file" "$config_file.bak"  >/dev/null 2>&1
    isgreen "备份配置文件"
fi
# 添加阿里云时间服务器
if ! grep -q aliyun "$config_file"; then
    # 清除默认的时间服务器配置
    sed -i '/^server/d' "$config_file"  >/dev/null 2>&1
    isgreen "清除默认的时间服务器配置"
    sed -i '2a\server ntp.aliyun.com iburst' "$config_file"  >/dev/null 2>&1
    isgreen "配置aliyun时间服务器"
fi
isgreen "complete"

# 启动服务
echo "启动服务"
systemctl enable chronyd --now >/dev/null 2>&1
isgreen "启动服务"

# 同步时间
echo "同步时间"
chronyc -a makestep

